package cn.cxyxj.inner_client_2.controller;

import cn.cxyxj.inner_client_2.utils.JWTUtil;
import cn.cxyxj.inner_client_2.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@RestController
public class HelloController {

    @Autowired
    RestTemplate restTemplate;


    /**
     * OAuth 登录回调地址
     * @param code
     * @return
     */
    @GetMapping("/codeLogin")
    public String hello(String code) {
        if (code != null) {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("code", code);
            map.add("client_id", "client-b");
            map.add("client_secret", "123456");
            map.add("redirect_uri", "http://localhost:8084/codeLogin");
            map.add("grant_type", "authorization_code");
            String resp = restTemplate.postForObject("http://localhost:8080/oauth/token", map, String.class);
            JSONObject tokenResult = JSON.parseObject(resp);
            System.out.println(tokenResult.toJSONString());

            String access_token = tokenResult.getString("access_token");
            String account = tokenResult.getString("account");
            String refresh_token = tokenResult.getString("refresh_token");

            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Bearer " + access_token);
            HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
            ResponseEntity<String> entity = restTemplate.exchange("http://localhost:8082/user/get-current-user", HttpMethod.GET, httpEntity, String.class);
            String body = entity.getBody();
            System.out.println(body);
            String token = JWTUtil.createToken(account);
            // 根据用户信息生成局部 token
            // RedisUtil.set("access_token:"+"",access_token);
            Object t = RedisUtil.get(String.format("access_token:%s", account));
            if(Objects.nonNull(t)) {
                Object tokenValue = RedisUtil.get(t.toString());
                String innerClientTokenKey = String.format("inner_client_token:%s", tokenValue);
                RedisUtil.del(innerClientTokenKey);
            }
            RedisUtil.set(String.format("access_token:%s",account),access_token);
            RedisUtil.set(String.format("refresh_token:%s",account),refresh_token);
            RedisUtil.set(String.format("inner_client_token:%s",token),access_token);
            RedisUtil.set(String.format("token:%s",account),token);
            return token;
        }
        return "EROOR";
    }


    @GetMapping("/inner-client-2")
    public String getclient1() {
        return "inner-client-2";
    }

    @GetMapping("/checkLogin")
    public void checkLogin(HttpServletResponse response) throws IOException {

        String checkLoginUrl ="http://localhost:8080/oauth/authorize" + "?response_type=" + "code"
                + "&client_id=client-a"
                + "&redirect_uri=" + URLEncoder.encode("http://localhost:8083/codeLogin", "UTF-8")
                + "&scope=" + "userinfo"
                + "&state=" + UUID.randomUUID();
        response.sendRedirect(checkLoginUrl);
    }


    @GetMapping("/logout")
    public void logout(@RequestParam String account, @RequestParam String accessToken)  {
        System.out.println(accessToken);
        String accessTokenKey = String.format("access_token:%s", account);
        Object accessTokenValue = RedisUtil.get(accessTokenKey);
        boolean b = Objects.isNull(accessTokenValue) ? false: accessTokenValue.equals(accessToken);
        if(b){
            String refreshTokenKey = String.format("refresh_token:%s", account);
            String tokenKey = String.format("token:%s", account);
            Object tokenValue = RedisUtil.get(tokenKey);
            String innerClientTokenKey = String.format("inner_client_token:%s", tokenValue);
            RedisUtil.del(accessTokenKey,refreshTokenKey,tokenKey,innerClientTokenKey);
            // 调用认证中心登出接口

        }
        System.out.println("登出状态 "+ b);
    }
}